package cn.gok.gokhappymall.controller;

import cn.gok.gokhappymall.common.ServerResponse;
import cn.gok.gokhappymall.entity.Product;
import cn.gok.gokhappymall.service.ProductService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: chenfan
 * @Description:
 */
@RestController
@RequestMapping("/manage/product")
public class ProductController {

    @Autowired
    ProductService productService;

    @GetMapping("/search.do")
    public ServerResponse<PageInfo<Product>> search(Integer productId, String productName, Integer pageNum, Integer pageSize){


        ServerResponse<PageInfo<Product>> productList = productService.search(productId,productName, pageNum, pageSize);

        return productList;
    }


    /**
       文件上传：
            1、先将图片临时保存到当前web服务器中
            2、再借助Ftp提供的客户端工具类，将图片上传至ftp服务器
            3、将web服务器中的图片删除
     */
    @PostMapping ("/upload.do")
    public ServerResponse upload(@RequestParam("upload_file") MultipartFile mf) throws IOException {

        /*
            获取项目的根路径的类路径
                    ResourceUtils.getURL("classpath:").getPath();
            获取项目路径下的根路径：
                    ResourceUtils.getURL("").getPath();
         */
        String path = ResourceUtils.getURL("classpath:").getPath();

        //在类路径下创建 static/upload路径
        File upload = new File(path,"static/upload");

        if (!upload.exists()){
            upload.mkdirs();
        }

        ServerResponse serverResponse = productService.upload(mf, upload.getAbsolutePath());
        return serverResponse;
    }





    @PostMapping ("/save.do")
    public ServerResponse saveOrUpdate(Product product) {

       if (product.getId() == null){
           productService.addProduct(product);

       }else {
           productService.updateProduct(product);
       }
       return null;
    }







}
